import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';

import '../extension/index.dart';
import '../ui/index.dart';

class CommonOperate {
  ///退出app
  static void exitApp() {
    if (Platform.isAndroid) {
      SystemNavigator.pop(animated: true);
    } else {
      exit(0);
    }
  }

  ///收起键盘
  static void hideKeyboard() {
    FocusManager.instance.primaryFocus?.unfocus();
  }

  ///下一帧刷新
  static void nextFrameRefresh(VoidCallback refresh) {
    SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
      refresh.call();
    });
    SchedulerBinding.instance.scheduleFrame();
  }

  ///复制文本
  static void copy(String text, {String? toast}) {
    Clipboard.setData(
      ClipboardData(text: text),
    );
    if (toast.empty) return;
    Loading.toast(toast!);
  }

  ///手机号转带*号的格式
  static String getEncryptionPhoneNum(String phone) {
    if (phone.length >= 7) {
      String front = phone.substring(0, 3);
      String end = phone.substring(phone.length - 4);
      return '$front****$end';
    }
    return phone;
  }
}

class UrlLauncherUtils {
  ///打电话
  static void makePhoneCall(String phone) {
    if (Loading.predicate(() => phone.empty, '电话号码不存在')) return;
    _realLaunch('tel:$phone');
  }

  ///发短信
  static void makeSmsCall(String phone) {
    if (Loading.predicate(() => phone.empty, '电话号码不存在')) return;
    _realLaunch('sms:$phone');
  }

  ///发邮件
  static void makeEmailCall(String email) => _realLaunch('mailto:$email');

  ///在系统浏览器中打开url
  static void openUrl(String url) => _realLaunch(url, mode: LaunchMode.externalApplication);

  ///执行
  static Future<bool> _realLaunch(String url, {LaunchMode? mode}) async {
    Uri uri = Uri.parse(url);
    if (await canLaunchUrl(uri)) {
      return await launchUrl(uri, mode: mode ?? LaunchMode.platformDefault);
    } else {
      Loading.toast('操作失败');
      return false;
    }
  }
}
